// src/services/recordsService.js

/**
 * 历史记录服务 - 负责与后端API通信
 */
class RecordsService {
  constructor(baseUrl = 'http://localhost:8000/records') {
    this.baseUrl = baseUrl;
  }

  /**
   * 获取用户的历史记录
   * @param {number} days - 获取多少天内的记录
   * @param {number} limit - 获取记录的最大数量
   * @returns {Promise<Array>} - 历史记录数组
   */
  async getRecords(days = 7, limit = 50) {
    try {
      const response = await fetch(`${this.baseUrl}?days=${days}&limit=${limit}`, {
        method: 'GET',
        headers: {
          'Authorization': `Bearer ${localStorage.getItem('token')}`,
          'Content-Type': 'application/json',
        },
      });

      if (!response.ok) {
        throw new Error(`获取历史记录失败: ${response.statusText}`);
      }

      return await response.json();
    } catch (error) {
      console.error('获取历史记录时出错:', error);
      throw error;
    }
  }

  /**
   * 获取用户历史记录统计数据
   * @returns {Promise<Object>} - 统计数据对象
   */
  async getStats() {
    try {
      const response = await fetch(`${this.baseUrl}/stats`, {
        method: 'GET',
        headers: {
          'Authorization': `Bearer ${localStorage.getItem('token')}`,
          'Content-Type': 'application/json',
        },
      });

      if (!response.ok) {
        throw new Error(`获取统计数据失败: ${response.statusText}`);
      }

      return await response.json();
    } catch (error) {
      console.error('获取统计数据时出错:', error);
      throw error;
    }
  }

  /**
   * 创建语音识别记录
   * @param {Object} asrRecord - 语音识别记录对象
   * @returns {Promise<Object>} - 创建的记录
   */
  async createAsrRecord(asrRecord) {
    try {
      const response = await fetch(`${this.baseUrl}/asr`, {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${localStorage.getItem('token')}`,
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(asrRecord),
      });

      if (!response.ok) {
        throw new Error(`创建ASR记录失败: ${response.statusText}`);
      }

      return await response.json();
    } catch (error) {
      console.error('创建ASR记录时出错:', error);
      throw error;
    }
  }

  /**
   * 创建翻译记录
   * @param {Object} translationRecord - 翻译记录对象
   * @returns {Promise<Object>} - 创建的记录
   */
  async createTranslationRecord(translationRecord) {
    try {
      const response = await fetch(`${this.baseUrl}/translation`, {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${localStorage.getItem('token')}`,
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(translationRecord),
      });

      if (!response.ok) {
        throw new Error(`创建翻译记录失败: ${response.statusText}`);
      }

      return await response.json();
    } catch (error) {
      console.error('创建翻译记录时出错:', error);
      throw error;
    }
  }
}

export default new RecordsService();
